package com.ruoyi.order.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.order.domain.Order;
import com.ruoyi.order.service.IOrderService;
import com.ruoyi.shop.domain.Shop;
import com.ruoyi.shop.service.IShopService;
import com.ruoyi.shopUserRelation.domain.UserShopRelation;
import com.ruoyi.shopUserRelation.service.IUserShopRelationService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/ruoyi/order/verification")
public class OrderVerificationController extends BaseController {

    @Autowired
    private IOrderService orderService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IShopService shopService;

    @Autowired
    private IUserShopRelationService userShopRelationService;

    @Autowired
    private SysLoginService loginService;

    @Autowired
    private TokenService tokenService;

//    其他权限控制方式
//    @ss.lacksPermi() - 检查用户是否不具有特定权限
//    @ss.hasAnyPermi() - 检查用户是否具有任意一个权限
//    @ss.lacksRole() - 检查用户是否不具有特定角色
//    @ss.hasAnyRoles() - 检查用户是否具有任意一个角色

    /**
     * 根据核销码查询订单信息
     */
    @PreAuthorize("@ss.hasRole('verifier')")
    @GetMapping(value = "/{verificationCode}")
    public AjaxResult getOrderInfo(@PathVariable("verificationCode") String verificationCode) {
        Order order = orderService.selectOrderByVerificationCode(verificationCode);
        if (order == null) {
            return AjaxResult.error("未找到对应的订单");
        }
        return AjaxResult.success(order);
    }

    /**
     * 核销订单 用作测试
     */
    @PreAuthorize("@ss.hasRole('verifier')")
    @Log(title = "订单核销", businessType = BusinessType.UPDATE)
    @PostMapping("/{verificationCode}")
    public AjaxResult verifyOrderWithAuth(@PathVariable("verificationCode") String verificationCode) {
        try {
            boolean result = orderService.verifyOrderWithAuth(verificationCode);
            if (result) {
                return AjaxResult.success("核销成功");
            } else {
                return AjaxResult.error("核销失败");
            }
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 接口 1：生成核销码接口（支付成功后触发）
     *
     * @param orderId 订单ID
     * @param orderCode 订单编号
     * @return 核销码信息
     */
    @PostMapping("/generate")
    public AjaxResult generateVerificationCode(@RequestParam Long orderId, @RequestParam String orderCode) {
        try {
            // 根据订单ID获取订单信息
            Order order = orderService.selectOrderByOrderId(orderId);

            // 验证订单信息
            if (order == null) {
                return AjaxResult.error(404, "订单不存在");
            }

            if (!orderCode.equals(order.getOrderCode())) {
                return AjaxResult.error(400, "订单编号不匹配");
            }

            // 检查订单状态，只有已支付的订单才能生成核销码
            if (!"1".equals(order.getMasterStatus())) {
                return AjaxResult.error(400, "只有已支付的订单才能生成核销码");
            }

            // 如果订单已经有核销码，则直接返回
            if (order.getVerificationCode() != null && !order.getVerificationCode().isEmpty()) {
                Map<String, Object> result = new HashMap<>();
                result.put("verificationCode", order.getVerificationCode());
                result.put("orderUseStatus", "待使用");
                return AjaxResult.success("核销码已存在", result);
            }

            // 生成核销码
            String verificationCode = orderCode + "_" + generateRandomString(5);

            // 更新订单的核销码
            order.setVerificationCode(verificationCode);
            order.setVerificationStatus("0"); // 待使用
            orderService.updateOrder(order);

            Map<String, Object> result = new HashMap<>();
            result.put("verificationCode", verificationCode);
            result.put("orderUseStatus", "待使用");

            return AjaxResult.success("核销码生成成功", result);
        } catch (Exception e) {
            logger.error("生成核销码失败", e);
            return AjaxResult.error("生成核销码失败: " + e.getMessage());
        }
    }

    /**
     * 接口 2：核销操作接口（店员核销时调用）
     *
     * @param userId 核销员用户ID
     * @param verificationCode 核销码
     * @param shopId 门店ID
     * @return 核销结果
     */
    @PostMapping("/verifyOrderByCode")
    public AjaxResult verifyOrderByCode(@RequestParam Long userId, @RequestParam String verificationCode, @RequestParam Long shopId) {
        try {
            // 1. 验证用户是否为核销员（roleId=108L）
            SysUser user = userService.selectUserById(userId);
            if (user == null) {
                return AjaxResult.error(404, "用户不存在");
            }

            // 检查用户是否具有核销员角色（假设roleId=108L为核销员角色）
            boolean isVerifier = false;
            if (user.getRoles() != null) {
                for (int i = 0; i < user.getRoles().size(); i++) {
                    if (user.getRoles().get(i).getRoleId() != null && user.getRoles().get(i).getRoleId() == 108L) {
                        isVerifier = true;
                        break;
                    }
                }
            }

            if (!isVerifier) {
                return AjaxResult.error(403, "用户无核销权限");
            }

            // 2. 验证门店是否存在
            Shop shop = shopService.selectShopByShopId(shopId);
            if (shop == null) {
                return AjaxResult.error(404, "门店不存在");
            }

            // 3. 根据核销码查询订单
            Order order = orderService.selectOrderByVerificationCode(verificationCode);
            if (order == null) {
                return AjaxResult.error(404, "未找到对应的订单");
            }

            // 4. 检查订单状态
            if (!"1".equals(order.getMasterStatus())) {
                return AjaxResult.error(400, "订单状态异常，无法核销");
            }

            // 5. 检查核销状态
            if (!"0".equals(order.getVerificationStatus())) {
                return AjaxResult.error(400, "订单已核销或状态异常");
            }

            // 6. 执行核销操作
            boolean result = orderService.verifyOrderWithAuth(verificationCode);
            if (result) {
                // 核销成功，返回详细信息
                Map<String, Object> data = new HashMap<>();
                data.put("orderId", order.getOrderId());
                data.put("orderCode", order.getOrderCode());
                data.put("verificationCode", order.getVerificationCode());
                data.put("orderUseStatus", order.getVerificationStatus());
                data.put("verificationTime", order.getVerificationTime());
                data.put("shopName", shop.getShopName());

                return AjaxResult.success("核销成功", data);
            } else {
                return AjaxResult.error(500, "核销失败");
            }
        } catch (Exception e) {
            logger.error("核销操作失败", e);
            return AjaxResult.error("核销操作失败: " + e.getMessage());
        }
    }

    /**
     * 接口 3：查询核销状态接口（用户 / 管理员查询）
     *
     * @param orderId 订单ID（可选）
     * @param verificationCode 核销码（可选）
     * @return 核销状态信息
     */
    @GetMapping("/status")
    public AjaxResult queryVerificationStatus(@RequestParam(required = false) Long orderId,
                                              @RequestParam(required = false) String verificationCode) {
        try {
            // 验证参数
            if (orderId == null && (verificationCode == null || verificationCode.isEmpty())) {
                return AjaxResult.error(400, "请提供订单ID或核销码");
            }

            Order order;
            if (orderId != null) {
                // 根据订单ID查询
                order = orderService.selectOrderByOrderId(orderId);
            } else {
                // 根据核销码查询
                order = orderService.selectOrderByVerificationCode(verificationCode);
            }

            if (order == null) {
                return AjaxResult.error(404, "未找到对应的订单");
            }

            // 构造返回数据
            Map<String, Object> data = new HashMap<>();
            data.put("orderId", order.getOrderId());
            data.put("orderCode", order.getOrderCode());
            data.put("verificationCode", order.getVerificationCode());
            data.put("orderUseStatus", order.getVerificationStatus());

            // 获取核销记录信息
            Map<String, Object> verifyRecord = new HashMap<>();
            if ("1".equals(order.getVerificationStatus()) && order.getVerificationTime() != null) {
                // 如果已核销，获取核销记录
                verifyRecord.put("verificationTime", order.getVerificationTime());
                // 这里可以添加更多核销员信息，需要根据实际业务确定如何获取
            }

            data.put("verifyRecord", verifyRecord);

            return AjaxResult.success("查询成功", data);
        } catch (Exception e) {
            logger.error("查询核销状态失败", e);
            return AjaxResult.error("查询核销状态失败: " + e.getMessage());
        }
    }

    /**
     * 接口 4：核销员登录接口（店员专属登录）
     *
     * @param loginBody 登录信息
     * @return 登录结果
     */
    @PostMapping("/login")
    public AjaxResult verifierLogin(@RequestBody LoginBody loginBody) {
        try {
            // 执行登录验证
            String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(),
                    loginBody.getCode(), loginBody.getUuid());

            // 获取登录用户信息
            SysUser user = userService.selectUserByUserName(loginBody.getUsername());
            if (user == null) {
                return AjaxResult.error(404, "用户不存在");
            }

            // 检查用户是否具有核销员角色（roleId=108L）
            boolean isVerifier = false;
            if (user.getRoles() != null) {
                for (int i = 0; i < user.getRoles().size(); i++) {
                    if (user.getRoles().get(i).getRoleId() != null && user.getRoles().get(i).getRoleId() == 108L) {
                        isVerifier = true;
                        break;
                    }
                }
            }

            if (!isVerifier) {
                return AjaxResult.error(403, "用户无核销权限");
            }

            // 获取用户关联的门店信息
            UserShopRelation relation = userShopRelationService.selectDefaultShopByUserId(user.getUserId());
            Shop shop = null;
            if (relation != null) {
                shop = shopService.selectShopByShopId(relation.getShopId());
            }

            // 构造返回数据
            Map<String, Object> data = new HashMap<>();
            data.put("userId", user.getUserId());
            data.put("name", user.getNickName());

            if (shop != null) {
                data.put("shopId", shop.getShopId());
                data.put("shopName", shop.getShopName());
            }

            data.put("token", token);

            return AjaxResult.success("登录成功", data);
        } catch (Exception e) {
            logger.error("核销员登录失败", e);
            return AjaxResult.error("登录失败: " + e.getMessage());
        }
    }

    /**
     * 生成指定长度的随机字符串
     *
     * @param length 长度
     * @return 随机字符串
     */
    private String generateRandomString(int length) {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        StringBuilder sb = new StringBuilder();
        java.util.Random random = new java.util.Random();
        for (int i = 0; i < length; i++) {
            sb.append(chars.charAt(random.nextInt(chars.length())));
        }
        return sb.toString();
    }
}
